<template>
  <div class="membership-center">
    <NavBar />
    
    <div class="membership-container">
      <!-- 页面头部 -->
      <div class="page-header">
        <h1>会员中心</h1>
        <p>管理您的会员服务，查看账单记录，享受专属权益</p>
      </div>

      <!-- 当前会员状态 -->
      <div class="current-membership" v-if="membershipInfo">
        <div class="membership-card" :class="cardClass">
          <div class="card-header">
            <div class="plan-info">
              <h2>{{ membershipInfo.plan_name }}</h2>
              <span class="status-badge" :class="statusClass">
                {{ getStatusText(membershipInfo.membership_status) }}
              </span>
            </div>
            <div class="expiry-info">
              <p v-if="membershipInfo.membership_status === 'active'">
                到期时间：{{ formatDate(membershipInfo.membership_end_date) }}
                <span v-if="isExpiringSoon" class="expiring-warning">（即将到期）</span>
              </p>
              <p v-else-if="membershipInfo.membership_status === 'expired'" class="expired-text">
                会员已过期，请续费继续使用
              </p>
            </div>
          </div>
          <div class="card-actions">
            <el-button 
              v-if="membershipInfo.membership_status === 'expired'" 
              type="primary" 
              size="large"
              @click="showRenewDialog"
            >
              立即续费
            </el-button>
            <el-button 
              v-else" 
              type="primary" 
              size="large"
              @click="showRenewDialog"
            >
              续费会员
            </el-button>
            <el-button 
              size="large"
              @click="showUpgradeDialog"
              v-if="membershipInfo.plan_type !== 'enterprise'"
            >
              升级会员
            </el-button>
          </div>
        </div>
      </div>

      <!-- 无会员状态 -->
      <div class="no-membership" v-else>
        <div class="empty-state">
          <i class="el-icon-crown"></i>
          <h3>您还未开通会员</h3>
          <p>开通会员享受更多权益，无限制创建应用</p>
          <el-button type="primary" size="large" @click="showPurchaseDialog">
            立即开通
          </el-button>
        </div>
      </div>

      <!-- 会员套餐对比 -->
      <div class="plans-comparison">
        <h2>会员套餐对比</h2>
        <div class="plans-grid">
          <div class="plan-card" v-for="plan in membershipPlans" :key="plan.plan_type">
            <div class="plan-header">
              <h3>{{ plan.name }}</h3>
              <div class="price">
                <span class="currency">¥</span>
                <span class="amount">{{ plan.price }}</span>
                <span class="period">/月</span>
              </div>
            </div>
            <div class="plan-features">
              <div class="feature-item">
                <i class="el-icon-check"></i>
                <span>应用数量：{{ plan.app_limit === -1 ? '无限制' : plan.app_limit + '个' }}</span>
              </div>
              <div class="feature-item" v-for="(feature, index) in parseFeatures(plan.features)" :key="index">
                <i class="el-icon-check"></i>
                <span>{{ feature }}</span>
              </div>
            </div>
            <div class="plan-actions">
              <el-button 
                type="primary" 
                size="large" 
                @click="purchasePlan(plan)"
                :disabled="membershipInfo && membershipInfo.plan_type === plan.plan_type"
              >
                {{ membershipInfo && membershipInfo.plan_type === plan.plan_type ? '当前套餐' : '选择套餐' }}
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 余额信息 -->
      <div class="balance-section" v-if="userBalance">
        <div class="balance-card">
          <div class="balance-header">
            <h3>账户余额</h3>
            <span class="balance-amount">¥{{ userBalance.balance }}</span>
          </div>
          <div class="balance-actions">
            <el-button type="primary" @click="showRechargeDialog">充值余额</el-button>
            <el-button @click="showBalanceHistory">余额记录</el-button>
          </div>
        </div>
      </div>

      <!-- 最近活动 -->
      <div class="recent-activities">
        <h2>最近活动</h2>
        <div class="activities-list">
          <div class="activity-item" v-for="activity in recentActivities" :key="activity.id">
            <div class="activity-icon">
              <i :class="getActivityIcon(activity.action)"></i>
            </div>
            <div class="activity-content">
              <div class="activity-title">{{ getActivityTitle(activity.action) }}</div>
              <div class="activity-time">{{ formatDateTime(activity.created_at) }}</div>
            </div>
          </div>
          <div class="empty-activities" v-if="recentActivities.length === 0">
            <i class="el-icon-time"></i>
            <p>暂无最近活动</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 余额充值对话框 -->
    <BalanceRechargeDialog
      v-model="rechargeDialogVisible"
      :current-balance="userBalance?.balance || 0"
      @success="handleRechargeSuccess"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import NavBar from '@/components/NavBarEnhanced.vue'
import BalanceRechargeDialog from '@/components/BalanceRechargeDialog.vue'
import { ElMessage } from 'element-plus'
import { getMembershipInfo, getMembershipPlans } from '@/api/membership'

export default {
  name: 'MembershipCenter',
  components: {
    NavBar,
    BalanceRechargeDialog
  },
  setup() {
    const router = useRouter()
    const membershipInfo = ref(null)
    const membershipPlans = ref([])
    const userBalance = ref(null)
    const recentActivities = ref([])
    const rechargeDialogVisible = ref(false)

    // 计算卡片样式
    const cardClass = computed(() => {
      if (!membershipInfo.value) return ''
      return `membership-${membershipInfo.value.plan_type}`
    })

    // 计算状态样式
    const statusClass = computed(() => {
      if (!membershipInfo.value) return ''
      return `status-${membershipInfo.value.membership_status}`
    })

    // 计算是否即将到期
    const isExpiringSoon = computed(() => {
      if (!membershipInfo.value || membershipInfo.value.membership_status === 'expired') {
        return false
      }
      
      const endDate = new Date(membershipInfo.value.membership_end_date)
      const now = new Date()
      const diffTime = endDate - now
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      
      return diffDays <= 7 && diffDays > 0
    })

    // 获取会员信息
    const loadMembershipInfo = async () => {
      try {
        const response = await getMembershipInfo()
        if (response.data.code === 200) {
          const data = response.data.data
          membershipInfo.value = data.limit_info
          userBalance.value = data.balance
          recentActivities.value = data.recent_activities || []
        }
      } catch (error) {
        console.error('获取会员信息失败:', error)
        ElMessage.error('获取会员信息失败')
      }
    }

    // 获取会员套餐
    const loadMembershipPlans = async () => {
      try {
        const response = await getMembershipPlans()
        if (response.data.code === 200) {
          membershipPlans.value = response.data.data
        }
      } catch (error) {
        console.error('获取会员套餐失败:', error)
        ElMessage.error('获取会员套餐失败')
      }
    }

    // 解析功能特性
    const parseFeatures = (features) => {
      if (!features) return []
      try {
        const featuresObj = JSON.parse(features)
        return [
          `客服支持：${featuresObj.support || '基础'}`,
          `数据分析：${featuresObj.analytics || '基础'}`,
          `存储空间：${featuresObj.storage || '1GB'}`
        ]
      } catch {
        return []
      }
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'active': '正常',
        'expired': '已过期',
        'cancelled': '已取消'
      }
      return statusMap[status] || status
    }

    // 格式化日期
    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN')
    }

    // 格式化日期时间
    const formatDateTime = (dateString) => {
      return new Date(dateString).toLocaleString('zh-CN')
    }

    // 获取活动图标
    const getActivityIcon = (action) => {
      const iconMap = {
        'app_create_success': 'el-icon-circle-plus',
        'app_create_attempt': 'el-icon-plus',
        'membership_purchase': 'el-icon-shopping-cart-full',
        'membership_renew': 'el-icon-refresh',
        'balance_recharge': 'el-icon-money',
        'balance_consume': 'el-icon-sold-out'
      }
      return iconMap[action] || 'el-icon-info'
    }

    // 获取活动标题
    const getActivityTitle = (action) => {
      const titleMap = {
        'app_create_success': '创建应用成功',
        'app_create_attempt': '尝试创建应用',
        'membership_purchase': '购买会员',
        'membership_renew': '续费会员',
        'balance_recharge': '余额充值',
        'balance_consume': '余额消费'
      }
      return titleMap[action] || '未知操作'
    }

    // 显示续费对话框
    const showRenewDialog = () => {
      ElMessage.info('续费功能开发中，敬请期待')
    }

    // 显示升级对话框
    const showUpgradeDialog = () => {
      ElMessage.info('升级功能开发中，敬请期待')
    }

    // 显示购买对话框
    const showPurchaseDialog = () => {
      ElMessage.info('购买功能开发中，敬请期待')
    }

    // 购买套餐
    const purchasePlan = (plan) => {
      ElMessage.info(`购买 ${plan.name} 功能开发中，敬请期待`)
    }

    // 显示充值对话框
    const showRechargeDialog = () => {
      rechargeDialogVisible.value = true
    }

    // 显示余额历史
    const showBalanceHistory = () => {
      router.push('/billing?type=balance')
    }

    // 处理充值成功
    const handleRechargeSuccess = () => {
      // 重新加载会员信息
      loadMembershipInfo()
      rechargeDialogVisible.value = false
    }

    onMounted(() => {
      loadMembershipInfo()
      loadMembershipPlans()
    })

    return {
      membershipInfo,
      membershipPlans,
      userBalance,
      recentActivities,
      rechargeDialogVisible,
      cardClass,
      statusClass,
      isExpiringSoon,
      parseFeatures,
      getStatusText,
      formatDate,
      formatDateTime,
      getActivityIcon,
      getActivityTitle,
      showRenewDialog,
      showUpgradeDialog,
      showPurchaseDialog,
      purchasePlan,
      showRechargeDialog,
      showBalanceHistory,
      handleRechargeSuccess
    }
  }
}
</script>

<style scoped>
.membership-center {
  min-height: 100vh;
  background: #f5f7fa;
}

.membership-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.page-header {
  text-align: center;
  margin-bottom: 3rem;
}

.page-header h1 {
  font-size: 2.5rem;
  color: #303133;
  margin-bottom: 0.5rem;
}

.page-header p {
  font-size: 1.1rem;
  color: #606266;
}

/* 当前会员状态 */
.current-membership {
  margin-bottom: 3rem;
}

.membership-card {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.membership-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.plan-info h2 {
  font-size: 1.8rem;
  color: #303133;
  margin: 0 0 0.5rem 0;
}

.status-badge {
  padding: 0.5rem 1rem;
  border-radius: 2rem;
  font-size: 0.875rem;
  font-weight: 500;
}

.status-active {
  background: #f0f9ff;
  color: #1890ff;
}

.status-expired {
  background: #fef0f0;
  color: #f56c6c;
}

.expiry-info {
  text-align: right;
}

.expiring-warning {
  color: #e6a23c;
  font-weight: 500;
}

.expired-text {
  color: #f56c6c;
  font-weight: 500;
}

.card-actions {
  display: flex;
  gap: 1rem;
}

/* 无会员状态 */
.no-membership {
  margin-bottom: 3rem;
}

.empty-state {
  background: white;
  border-radius: 1rem;
  padding: 4rem 2rem;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.empty-state i {
  font-size: 4rem;
  color: #c0c4cc;
  margin-bottom: 1rem;
}

.empty-state h3 {
  font-size: 1.5rem;
  color: #303133;
  margin-bottom: 0.5rem;
}

.empty-state p {
  color: #606266;
  margin-bottom: 2rem;
}

/* 会员套餐对比 */
.plans-comparison {
  margin-bottom: 3rem;
}

.plans-comparison h2 {
  font-size: 2rem;
  color: #303133;
  margin-bottom: 2rem;
  text-align: center;
}

.plans-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 2rem;
}

.plan-card {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.plan-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.plan-header {
  text-align: center;
  margin-bottom: 2rem;
}

.plan-header h3 {
  font-size: 1.5rem;
  color: #303133;
  margin-bottom: 1rem;
}

.price {
  display: flex;
  align-items: baseline;
  justify-content: center;
  gap: 0.25rem;
}

.currency {
  font-size: 1.2rem;
  color: #606266;
}

.amount {
  font-size: 2.5rem;
  font-weight: bold;
  color: #303133;
}

.period {
  font-size: 1rem;
  color: #909399;
}

.plan-features {
  margin-bottom: 2rem;
}

.feature-item {
  display: flex;
  align-items: center;
  margin-bottom: 1rem;
}

.feature-item i {
  color: #67c23a;
  margin-right: 0.5rem;
}

.plan-actions {
  text-align: center;
}

/* 余额信息 */
.balance-section {
  margin-bottom: 3rem;
}

.balance-card {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.balance-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.balance-header h3 {
  font-size: 1.5rem;
  color: #303133;
  margin: 0;
}

.balance-amount {
  font-size: 2rem;
  font-weight: bold;
  color: #67c23a;
}

.balance-actions {
  display: flex;
  gap: 1rem;
}

/* 最近活动 */
.recent-activities {
  margin-bottom: 3rem;
}

.recent-activities h2 {
  font-size: 2rem;
  color: #303133;
  margin-bottom: 2rem;
}

.activities-list {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.activity-item {
  display: flex;
  align-items: center;
  padding: 1rem 0;
  border-bottom: 1px solid #f0f0f0;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-icon {
  width: 3rem;
  height: 3rem;
  background: #f0f9ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 1rem;
}

.activity-icon i {
  color: #1890ff;
  font-size: 1.2rem;
}

.activity-content {
  flex: 1;
}

.activity-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 0.25rem;
}

.activity-time {
  color: #909399;
  font-size: 0.875rem;
}

.empty-activities {
  text-align: center;
  padding: 3rem 0;
  color: #c0c4cc;
}

.empty-activities i {
  font-size: 3rem;
  margin-bottom: 1rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .membership-container {
    padding: 1rem;
  }
  
  .card-header {
    flex-direction: column;
    text-align: center;
  }
  
  .plans-grid {
    grid-template-columns: 1fr;
  }
  
  .balance-header {
    flex-direction: column;
    text-align: center;
  }
  
  .balance-actions {
    justify-content: center;
  }
}
</style>